package com.wolfman.socket.client;

/**
 * @Title
 * @Description
 * @Author WolfMan
 * @Date 2022/11/25 11:31
 * @Email 2370032534@qq.com
 */

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Client {


    private static final String DEFAULT_SERVER_HOST = "127.0.0.1";
    private static final int DEFAULT_SERVER_PORT = 8000;

    public static void main(String[] args) {
        Socket socket = null;
        BufferedWriter writer = null;
        BufferedReader reader = null;
        BufferedReader consoleReader = null;
        try {
            // 创建socket
            socket = new Socket(DEFAULT_SERVER_HOST, DEFAULT_SERVER_PORT);
            // 创建IO流
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
            // 等待用户输入信息
            consoleReader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
            while (true) {
                String input = consoleReader.readLine();
                // 发送消息给服务器
                writer.write(input + "\n");
                writer.flush();
                // 读取服务器返回的消息
                String msg = reader.readLine();
                System.out.println(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(socket, writer, reader, consoleReader);
        }

    }

    private static void close(Socket socket, BufferedWriter writer, BufferedReader reader, BufferedReader consoleReader) {
        try {
            if (reader != null) {
                reader.close();
            }
            if (writer != null) {
                writer.close();
            }
            if (socket != null) {
                socket.close();
            }
            if (consoleReader != null) {
                consoleReader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

